package com.jlcloud.core.cloud.feign;

import com.alibaba.cloud.commons.lang.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import com.jlcloud.core.tool.constant.JlCloudConstant;
import com.jlcloud.core.tool.utils.ThreadLocalUtil;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;

/**
 * feign 传递Request header
 *
 * <p>
 *     https://blog.csdn.net/u014519194/article/details/77160958
 *     http://tietang.wang/2016/02/25/hystrix/Hystrix%E5%8F%82%E6%95%B0%E8%AF%A6%E8%A7%A3/
 *     https://github.com/Netflix/Hystrix/issues/92#issuecomment-260548068
 * </p>
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
public class JlCloudFeignRequestInterceptor implements RequestInterceptor {

	private static final String UNIQUE_ID = "traceId";

	@Override
	public void apply(RequestTemplate requestTemplate) {
		// header中是否存在TraceId的标识
		BooleanWrapper traceIdEmpty = new BooleanWrapper(Boolean.TRUE);
		HttpHeaders headers = ThreadLocalUtil.get(JlCloudConstant.CONTEXT_KEY);
		if (headers != null && !headers.isEmpty()) {
			headers.forEach((key, values) -> {
				values.forEach(value -> requestTemplate.header(key, value));
				if (StringUtils.equals(key, UNIQUE_ID)) {
					traceIdEmpty.setValue(Boolean.FALSE);
				}
			});
		}
		// 为解决定时任务在调用feign接口时TraceId的问题，做以下处理： 如果header中不存在并且MDC中存在，则将TraceId加入到header
		if (Boolean.TRUE.equals(traceIdEmpty.getValue()) && StringUtils.isNotBlank(getTraceIdFromMDC())) {
			requestTemplate.header(UNIQUE_ID, getTraceIdFromMDC());
		}
	}

	static class BooleanWrapper {
		private Boolean value;

		public BooleanWrapper(Boolean value) {
			this.value = value;
		}

		public Boolean getValue() {
			return value;
		}

		public void setValue(Boolean value) {
			this.value = value;
		}
	}
	private String getTraceIdFromMDC() {
		return MDC.get(UNIQUE_ID);
	}

}
